package xin.marcher.module.message.mq.consumer.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xin.marcher.module.common.domain.BinlogData;
import xin.marcher.module.common.enums.message.BinlogType;
import xin.marcher.module.common.utils.message.BinlogUtils;
import xin.marcher.module.message.service.MessageService;

import java.util.List;
import java.util.Objects;

/**
 *
 */
@Slf4j
@Component
public class DataChangeListener implements MessageListenerConcurrently {

    @Autowired
    private MessageService messageService;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        try {
            for (MessageExt messageExt : list) {
                String msg = new String(messageExt.getBody());
                log.info("DataChangeListener数据变更消息通知，消息内容：{}", msg);

                // 获取binlog对象
                BinlogData binlogData = BinlogUtils.getBinlogData(msg);
                if (Objects.isNull(binlogData) || Objects.isNull(binlogData.getDataMap())) {
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }

                // 操作类型不是insert，delete，update的，不作处理
                String operateType = binlogData.getOperateType();
                if (!BinlogType.INSERT.getValue().equals(operateType)
                        && !BinlogType.DELETE.getValue().equals(operateType)
                        && !BinlogType.UPDATE.getValue().equals(operateType)) {
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }

                messageService.processBinlogMessage(binlogData);

            }
        } catch (Exception e) {
            log.error("consume error, 消费数据变更消息失败", e);
            // 本次消费失败，下次重新消费
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }

        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

}
